<template>
    <div class="app-container">
        <div style="margin-bottom: 20px">
            <el-input
                v-model="listQuery.username"
                placeholder="用户名/ID"
                style="width: 180px;"
                class="filter-item"
                @input="handleFilter"
            />
            <el-select
                v-model="listQuery.roles"
                style="margin-left: 10px"
                placeholder="用户角色"
                multiple
                @change="handleFilter"
            >
                <el-option label="编辑者" :value="1" />
                <el-option label="教师" :value="2" />
            </el-select>
            <el-button style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">新增用户</el-button>
            <batch-add style="display: inline-block; margin-left: 10px" @create-success="handleBatchAdd" />
        </div>

        <el-table
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width: 100%"
        >
            <el-table-column
                label="ID"
                align="center"
                width="100"
                prop="id"
            />

            <el-table-column
                label="用户名"
                min-width="140px"
                prop="username"
            />

            <el-table-column
                label="邮箱"
                min-width="170px"
                prop="email"
            />

            <el-table-column
                label="联系方式"
                min-width="120px"
                prop="phone"
            />

            <el-table-column class-name="status-col" label="角色" width="120">
                <template slot-scope="{row}">
                    <el-tag :type="row.role | roleTypeFilter">
                        {{ row.role | roleNameFilter }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column
                label="创建时间"
                width="180px"
                align="center"
                prop="createTime"
                sortable
            />

            <el-table-column align="center" label="操作" width="260">
                <template slot-scope="{row}">
                    <router-link :to="'/teacher/edit/'+row.id">
                        <el-button
                            :style="{visibility: row.role === 2 ? 'visible' : 'hidden'}"
                            type="primary"
                            size="small"
                            icon="el-icon-user-solid"
                        />
                    </router-link>
                    <el-button
                        type="primary"
                        size="small"
                        icon="el-icon-edit"
                        style="margin-left: 10px;"
                        plain
                        @click="handleUpdate(row)"
                    />
                    <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(row)" />
                </template>
            </el-table-column>

        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <!--创建/编辑用户基本信息-->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="600px" top="10vh">
            <el-form
                ref="dataForm"
                v-loading="formLoading"
                :rules="rules"
                :model="temp"
                label-position="left"
                label-width="90px"
                style="margin: 0 100px 0 50px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="temp.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="temp.password" type="password" />
                </el-form-item>
                <el-form-item v-if="displayCheckPwd" label="确认密码" prop="checkPass">
                    <el-input v-model="temp.checkPass" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色" prop="role" style="margin-bottom: 50px">
                    <!--创建时为可选角色-->
                    <el-select
                        v-if="dialogStatus === 'create'"
                        v-model="temp.role"
                        placeholder="用户角色"
                    >
                        <el-option label="编辑者" :value="1" />
                        <el-option label="教师" :value="2" />
                    </el-select>
                    <!--编辑时角色固定-->
                    <el-tag
                        v-if="dialogStatus === 'update'"
                        :type="temp.role | roleTypeFilter"
                    >
                        {{ temp.role | roleNameFilter }}
                    </el-tag>
                </el-form-item>
                <el-divider content-position="left">选填信息</el-divider>
                <el-form-item label="邮箱" prop="email" style="margin-top: 35px">
                    <el-input v-model="temp.email" />
                </el-form-item>
                <el-form-item label="联系方式" prop="phone">
                    <el-input v-model="temp.phone" />
                </el-form-item>
                <el-form-item label="密保问题" prop="question">
                    <el-input v-model="temp.question" />
                </el-form-item>
                <el-form-item label="密保答案" prop="answer">
                    <el-input v-model="temp.answer" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
                    {{ dialogStatus==='create'?'创建用户':'保存修改' }}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { adminUpdateUser, createUser, deleteUser, getUserList } from '@/api/user'
import { convertListToParam } from '@/utils/axios-formatter'
import BatchAdd from '@/views/user/user-list/components/batch-add' // Secondary package based on el-pagination

export default {
    name: 'UserList',
    components: { BatchAdd, Pagination },
    filters: {
        roleTypeFilter(role) {
            const roleMap = {
                0: 'error',
                1: 'info',
                2: 'success'
            }
            return roleMap[role]
        },
        roleNameFilter(role) {
            const roleMap = {
                0: '管理员',
                1: '编辑者',
                2: '教师'
            }
            return roleMap[role]
        }
    },
    data() {
        var validatePwd = (rule, value, callback) => {
            // 如果第一次编辑密码的时候, 显示再次输入密码
            if (this.dialogStatus === 'update' &&
                this.displayCheckPwd === false &&
                this.formLoading === false) {
                this.temp.password = ''
                this.displayCheckPwd = true
            }
            // 基本验证
            if (value === '') {
                callback(new Error('请输入密码'))
            } else if (value.length < 6) {
                callback(new Error('密码不能小于6位'))
            } else {
                callback()
            }
        }
        var validatePwd2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.temp.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            list: null,
            total: 0,
            listLoading: true,
            // 检索用户的筛选参数
            listQuery: {
                page: 1,
                limit: 20,
                username: '',
                roles: []
            },
            // 创建,编辑用户
            temp: {
                id: undefined,
                username: '',
                password: '',
                checkPass: '',
                email: '',
                phone: '',
                question: '',
                answer: '',
                role: undefined
            },
            dialogFormVisible: false,
            displayCheckPwd: true,
            dialogStatus: '',
            formLoading: false,
            textMap: {
                update: '编辑用户信息',
                create: '创建用户'
            },
            // 表单规则, 在超级管理员处, 邮箱和手机号可以为空
            rules: {
                username: [{ required: true, message: '用户名不能为空', trigger: ['blur', 'change'] }],
                password: [
                    { validator: validatePwd, trigger: 'change' },
                    { required: true }
                ],
                checkPass: [
                    { validator: validatePwd2, trigger: ['change', 'blur'] },
                    { required: true }
                ],
                email: [{
                    type: 'email',
                    message: '请输入正确的邮箱地址',
                    trigger: ['blur', 'change']
                }],
                phone: [{
                    pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
                    message: '请输入正确的手机号或者座机号(区号-尾号)'
                }],
                role: [{ required: true, message: '必须指定角色', trigger: 'change' }]
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        getList() {
            this.listLoading = true
            const _query = Object.assign({}, this.listQuery)
            _query.roles = convertListToParam(this.listQuery.roles)
            getUserList(_query).then(data => {
                this.list = data.content
                this.total = data.totalSize
                this.listLoading = false
            })
        },
        handleFilter() {
            this.getList()
            this.listQuery.page = 1
        },
        deleteUser(row) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteUser(row.id).then(() => {
                    const index = this.list.findIndex(v => v.id === row.id)
                    this.list.splice(index, 1)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 刷新提交表单, 如果传参则用传入数据填充字段
        resetTemp(data = null) {
            this.temp = {
                id: undefined,
                username: '',
                password: '',
                checkPass: '',
                phone: '',
                question: '',
                answer: '',
                role: undefined
            }
            if (data) {
                Object.assign(this.temp, data)
            }
        },
        handleCreate() {
            this.dialogStatus = 'create'
            this.resetTemp()
            this.displayCheckPwd = true
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.formLoading = true
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const _data = Object.assign({}, this.temp)
                    delete _data.checkPass
                    createUser(_data).then(user => {
                        this.list.unshift(user)
                        setTimeout(() => {
                            this.formLoading = false
                            this.dialogFormVisible = false
                            this.$notify({
                                keywords: 'Success',
                                message: '用户创建成功',
                                type: 'success',
                                duration: 2000
                            })
                        }, 500)
                    }).catch(() => { this.formLoading = false })
                } else {
                    this.formLoading = false
                }
            })
        },
        handleUpdate(row) {
            this.dialogStatus = 'update'
            this.resetTemp(row)
            this.temp.password = '●●●●●●' // 密码六个点
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.displayCheckPwd = false // 必须再下一个周期再改变,不然会导致更改密码事件执行
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.formLoading = true
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const _data = Object.assign({}, this.temp)
                    delete _data.checkPass
                    delete _data.createTime
                    delete _data.updateTime
                    if (this.temp.password === '' || this.temp.password === '●●●●●●') {
                        delete _data.password
                    }
                    adminUpdateUser(_data).then(() => {
                        const index = this.list.findIndex(v => v.id === this.temp.id)
                        this.list.splice(index, 1, this.temp)
                        setTimeout(() => {
                            this.formLoading = false
                            this.dialogFormVisible = false
                            this.$notify({
                                keywords: 'Success',
                                message: '用户更新成功',
                                type: 'success',
                                duration: 2000
                            })
                        }, 500)
                    }).catch(() => {
                        this.formLoading = false
                    })
                } else {
                    this.formLoading = false
                }
            })
        },
        // 处理批量新增
        handleBatchAdd(list) {
            list.forEach(item => {
                this.list.unshift(item)
            })
            this.$notify({
                keywords: 'Success',
                message: '用户批量创建成功',
                type: 'success',
                duration: 2000
            })
        }
    }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
